package com.lr.chat;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class Send implements Runnable{

	private DataOutputStream dos;
	
	private BufferedReader console;
	
	private boolean isRunning = true;
	
	private String name;
	
	public Send(){
		console = new BufferedReader(new InputStreamReader(System.in));
	}
	
	public Send(Socket socket,String name){
		this();
		try {
			dos = new DataOutputStream(socket.getOutputStream());
			this.name = name;
			sendMsg(name);
		} catch (IOException e) {
			stop();
			IOUtil.IOClose(dos,console);
		}
	}
	
	public String getMsgFromConsole(){
		String msg = null;
		try {
			 msg = console.readLine();
		} catch (IOException e) {
			stop();
			IOUtil.IOClose(dos,console);
		}
		return msg;
	}
	
	public void sendMsg(String msg){
		try {
			if(null != msg && !("").equals(msg)){
				dos.writeUTF(msg);
				dos.flush();
			}
		} catch (IOException e) {
			stop();
			IOUtil.IOClose(dos,console);
		}
	}
	 
	@Override
	public void run() {
        while(isRunning){
        	String msg = getMsgFromConsole();
        	sendMsg(msg);
        }
	}

	public void stop(){
		isRunning = false;
	}
}
